#!/bin/sh

#
# Test MBR extended partition creation
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
# Numbers don't matter for the test so long as the MBR is right
define(AUTOBOOT_PART_OFFSET, 64)
define(AUTOBOOT_PART_COUNT, 1984)
define(BOOT_A_PART_OFFSET, 2048)
define(BOOT_A_PART_COUNT, 65536)
define(BOOT_B_PART_OFFSET, 67584)
define(BOOT_B_PART_COUNT, 65536)
define(EXTENDED_PART_OFFSET, 133120)
define(ROOTFS_A_PART_OFFSET, 133376)
define(ROOTFS_A_PART_COUNT, 2097152)
define(ROOTFS_B_PART_OFFSET, 2230528)
define(ROOTFS_B_PART_COUNT, 2097152)
define(APP_PART_OFFSET, 4327680)
define(APP_PART_COUNT, 4194304)

mbr mbr-a {
    partition 0 {
        block-offset = \${AUTOBOOT_PART_OFFSET}
        block-count = \${AUTOBOOT_PART_COUNT}
        type = 0x6 # FAT12
        boot = true
    }
    partition 1 {
        block-offset = \${BOOT_A_PART_OFFSET}
        block-count = \${BOOT_A_PART_COUNT}
        type = 0xc # FAT32
    }
    partition 2 {
        block-offset = \${BOOT_B_PART_OFFSET}
        block-count = \${BOOT_B_PART_COUNT}
        type = 0xc # FAT32
    }
    partition 3 {
        type = 0xf # Extended partition
        block-offset = \${EXTENDED_PART_OFFSET}
    }
    partition 4 {
        block-offset = \${ROOTFS_A_PART_OFFSET}
        block-count = \${ROOTFS_A_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 5 {
        block-offset = \${ROOTFS_B_PART_OFFSET}
        block-count = \${ROOTFS_B_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 6 {
        block-offset = \${APP_PART_OFFSET}
        block-count = \${APP_PART_COUNT}
        type = 0x83 # Linux
    }
}

task complete {
	on-init {
                mbr_write(mbr-a)
        }
}
EOF

# Create the expected by running base64 on the expected binary image.
# dd if=fwup.img skip=0 count=1 | base64 -b 76
base64_decode >$WORK/expected_mbr.img <<EOF
AAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

# The firmware file is equivalent to the following dd call
cmp_bytes 512 $WORK/expected_mbr.img $IMGFILE 0 0
cmp_bytes 2048 $WORK/expected_ebr.img $IMGFILE 0 68157440

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
